/**
 * 初始化整体客户图标
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');
    var zrnumber = require('echarts/util/number');

    var myChart1 = ec.init(document.getElementById('customer_transfer_num')); 

    var option_1 = {

        tooltip : {
            trigger: 'axis',
            formatter: tooltipFunc_1
        },
        legend: {
            data:['转精准客户','转置顶客户','流失客户']
        },
        toolbox: {
            show : true,
            showTitle: true,
            orient:'vertical',
            feature : {
                mark : {show: true},
                dataZoom : {show: true},
                magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        grid: {
            y: 60,
            y2:25
        },
        dataZoom: {
           show: true,
           height: 20,
           realtime : true,
           start: 90
        },        
        xAxis: [{
            type: "category",
            position:'top',
            boundaryGap: true,
            data:[''],
            axisLabel:{formatter:function(value){
                return value.substr(0,4)+"-"+value.substr(4,2)+"-"+value.substr(6,2);
            }}
        }],
        yAxis: [
            {
                type: 'value'
            }
        ],

        series: [
           
        ]
    };
var nameMap_0 = {"tojingzhun#user_num":"转精准客户","tozhiding#user_num":"转置顶客户","flow#user_num":"流失客户"};
var nameMap_1 = {"tojingzhun#user_num_per":"转精准客户","tozhiding#user_num_per":"转置顶客户","flow#user_num_per":"流失客户"};
// 图例一一对应
    /**
     * 根据指标显示日数据
     * @param eventType= 2:第一次加载, 1:切换日，周，月刷新 , 0: 添加对比后又重新选择指标
     */
    function show(businessName,eventType){
        var dateGrp = $('#customertransferOption').attr('dateGrp');
        var statType = $('#customertransferOption').attr('statType');
        var customerType = $('#customertransferOption').attr('TransferindexType');
        var numType = $('#customertransferOption').attr('NumType');
        myChart1.showLoading({ text: '正在努力的读取数据中...' });
        $.ajax({
            url: '/dashboard/income/ajax/customerNumForTransfer',
            type: 'post',
            async: true,
            data:{"dateGroup":dateGrp,"statType":statType,"businessName":businessName,"customerSource":customerType,"numType":numType,"dataType":"chart"},
            dataType: 'json',
            success: function(data, textStatus) {
                //X轴时间
                option_1.xAxis[0].data = data.time;
                var nameMap={};
                //上图每条曲线
                var i = 0;
                var series_local = [];
                if('user_num_per'==numType)
                {
                    nameMap=nameMap_1;
                }else
                {
                    nameMap=nameMap_0;
                }

                $.each(nameMap,function(colName,name){
                    series_local[i++] = {
                        name: name,
                        type: 'bar',
                        smooth: true,
                        stack: '总量',
                        symbol:'none',
                        itemStyle: {normal: {areaStyle: {type: 'default'}}},
                        'data': data[colName]
                    };
                });
                option_1.series = series_local;       

                //区域缩放
                var datezoom_local={
                    week_num:{start:(1-12/data.time.length)*100,end:100},
                    month_num:{start:0,end:100},
                };
                //少于31个点，全显
                if(data.time.length<31){
                    datezoom_local={
                        week_num:{start:0,end:100},
                        month_num:{start:0,end:100},
                    };
                }

               
                if('week_num'==dateGrp){      
                    option_1.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                }else if('month_num'==dateGrp){
                    option_1.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(5,2)+"月"; } ;
                }
                option_1.dataZoom.start=datezoom_local[dateGrp].start;
                option_1.dataZoom.end=datezoom_local[dateGrp].end;
                if(eventType == 1 ){
                    myChart1.component.dataZoom.absoluteZoom(datezoom_local[dateGrp]);
                }else if(eventType == 2){
                   
                }
                option_1.dataZoom.show=true;
                myChart1.setOption(option_1,true);
                // myChart.clear();
                myChart1.hideLoading();
            },
            error : function() {
                myChart1.hideLoading();
            }
        });
    }

    //图例选择事件
    var ecConfig = require('echarts/config');
    function eventClick(param){
        var click_date = '2014-01-01';
        if (typeof param.seriesIndex != 'undefined') {
            click_date = param.name;
        }else{
            return;
        }
        loadTableData(click_date);
    }
    myChart1.on(ecConfig.EVENT.CLICK, eventClick);

    //加载转置顶客户当天的数据，, 0:字符, 1:数字, 2:百分比
    var show_cols = {"product_type":0,"tojingzhun#user_num":1,"tojingzhun#user_num_per":1,"tojingzhun#user_num_chain":2,"tozhiding#user_num":1,"tozhiding#user_num_per":1,
    "tozhiding#user_num_chain":2,"flow#user_num":1,"flow#user_num_per":1,"flow#user_num_chain":2};
    var mapdata={"jingzhun":0,"zhiding":1};
    var nameMap={"jingzhun":"精准","zhiding":"置顶"};
    function loadTableData(stat_date){
        var statType = $('#customertransferOption').attr('statType');
        var customerType = $('#customertransferOption').attr('TransferindexType');
        var businessName = cate;
        $.ajax({
            url: '/dashboard/income/ajax/customerNumForTransfer',
            type: 'post',
            async: true,
            data:{"statType":statType,"businessName":businessName,"dateVal":stat_date,"customerSource":customerType,"dataType":"table"},
            dataType: 'json',
            success: function(data, textStatus) {
                var resultList = data.dataList;
                var res=[];
                res[0]={};res[1]={};
                $.each(resultList,function(i,vo){   
                       res[mapdata[vo['product_type']]]['product_type']=nameMap[vo['product_type']];
                        $.each(vo,function(col,colnumber){
                            if(col=="user_num"||col=="user_num_chain"||col=="user_num_per")
                            {
                                 res[mapdata[vo['product_type']]][vo['user_type']+'#'+col]=colnumber;
                            }

                        });
                    
                });
                var htmlRows = "";
                $.each(res,function(i,vo){
                    htmlRows += "<tr>";
                    $.each(show_cols,function(col,colType){
                        switch(colType){
                            case 0:
                                htmlRows += "<td>";
                                htmlRows += vo[col];
                                htmlRows += "</td>";
                                break;
                            case 1:
                                htmlRows += "<td>";
                                htmlRows += zrnumber.addCommas(formatNum(vo[col]));
                                htmlRows += "</td>";
                                break;
                            case 2:
                                htmlRows += getRate(vo[col]);
                                break;
                        }
                    });

                    htmlRows += "</tr>";
                });

                $('#customerTransferTable tr:gt(0)').remove();
                $('#customerTransferTable_data').text(stat_date.replace(/\-/g,"."));
                $('#customerTransferTable').append(htmlRows);
            },
            error : function() {

            }
        }); 
    }

    var all_Options = [option_1];
    function tooltipFunc_1(params, ticket, callback){
        return tooltipFunc(params, ticket, callback,0);
    }
    function tooltipFunc_2(params, ticket, callback){
        return tooltipFunc(params, ticket, callback,1);
    }
    //提示框
    function  tooltipFunc(params, ticket, callback,optionIndex){
        var dateVal = params[0].name;
        var curOption = all_Options[optionIndex];
        var index_current=getIndexByName(curOption.xAxis[0].data,dateVal);

        var result='<table class="table-center">';
        result+='<tr><td>'+dateVal+'</td><td>';
        var isStatDay = isDay(); 
        if(isStatDay)
            result += getWeekDay(dateVal);
        result += '</td><td>占比</td>';
        if(isStatDay)
            result +="<td>日环比</td><td>周同比</td>";
        else if(isWeek())
            result += "<td>周环比</td>";
         else if(isMonth())
            result += "<td>月环比</td>";
        result += '</tr>';

        var total=0;

        $(params).each(function(index,para){
            if(para.data<0)
              total+=0-para.data;
            else
              total+=para.data;
        });

        $(params).each(function(index,para){
            var s=((para.data/total)*100).toFixed(2);
            if(s<0)
                s=0-s;
            result+='<tr><td>'+para.seriesName+'</td><td>'+zrnumber.addCommas(formatNum(para.data))+'</td><td>'+s+'%</td>';

            var seriesIndex = para.seriesIndex;
            var day_td="<td>--</td>";
            //日周月 环比(前一日周月)
            if(index_current-1>=0){
                var data_yesday = null;
                //去年同月
                if(isMonth()){
                    if(index_current-1>=0){
                        data_yesday= curOption.series[seriesIndex].data[index_current-1];
                    }
                }else{ 
                    data_yesday= curOption.series[seriesIndex].data[index_current-1];                
                }
                if(data_yesday != null){
                    var s=(((para.data/data_yesday)-1)*100).toFixed(2);
                    if(s>0){
                        day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
            }
            result += day_td;
            //周同比(日)
            if(isStatDay){
                var week_td='<td>--</td>';
                if(index_current-7>=0){
                    data_week= curOption.series[seriesIndex].data[index_current-7];
                    var s=(((para.data/data_week)-1)*100).toFixed(2);
                    if(s>0){
                        week_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        week_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
                result += week_td;
            }
            result += '</tr>';
        });
        result+='</table>';
        return result;
    }           

   function formatShowDate(yyyymmdd){
        var dateGrp = $('#customertransferOption').attr('dateGrp');
        if('stat_date'==dateGrp){
            return yyyymmdd;
        }else if('week_num'==dateGrp){
            return yyyymmdd;
        }else if('month_num'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(5,2)+"月";
        }
    }

    function isDay(){
        var dateGrp = $('#customertransferOption').attr('dateGrp');
        if('stat_date'==dateGrp){
            return true;
        }
        return false;
    }

        function isWeek(){
         var dateGrp = $('#customertransferOption').attr('dateGrp');
        if('week_num'==dateGrp){
            return true;
        }
        return false;
    }

    function isMonth(){
        var dateGrp = $('#customertransferOption').attr('dateGrp');
        if('month_num'==dateGrp){
            return true;
        }
        return false;
    }

    var zrUtil = require('zrender/tool/util');
    // console.log(zrUtil);

    //添加对比--图一
    function addCompare_1(time){
        time=formatTime(time);
        var copy=zrUtil.clone(option_1);
        copy.toolbox.feature.magicType.show=false;
        copy.toolbox.feature.dataZoom.show=false;
        var index_time=getIndexByName(option_1.xAxis[0].data,time);
        var index_show=getIndexByName(option_1.xAxis[0].data,getShowDays()[0]);
        var length=getShowDays().length;
        setCompareXaxis(option_1,copy,index_time,index_show,length);
        var index=0;
        //选中对比时，再次选择指标，需要记忆图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            //判断是否在当前图例值中，应为echarts会把"对比时间段"也放入SelectedMap
            if($.inArray(key,option_1.legend.data) != -1){
                if(value){
                    return false;
                }
                index++;
            }     
        });
        // console.log(index);
        if(index<3){
            setCompareSeries(option_1,copy,index,index_time,index_show,length);
            setCompareLegend(copy);
            setCompareTooltip(copy);
            delete copy.dataZoom;
            myChart1.restore();
            myChart1.setOption(copy,true);
        }

    }

    //添加对比--图二
    function addCompare_2(time){
        time=formatTime(time);
        var copy=zrUtil.clone(option_2);
        copy.toolbox.feature.magicType.show=false;
        copy.toolbox.feature.dataZoom.show=false;
        var index_time=getIndexByName(option_2.xAxis[0].data,time);
        var index_show=getIndexByName(option_2.xAxis[0].data,getShowDays()[0]);
        var length=getShowDays().length;
        setCompareXaxis(option_2, copy,index_time,index_show,length);
        var index=0;
        //选中对比时，再次选择指标，需要记忆图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            //判断是否在当前图例值中，应为echarts会把"对比时间段"也放入SelectedMap
            if($.inArray(key,option_2.legend.data) != -1){
                if(value){
                    return false;
                }
                index++;
            }     
        });
        // console.log(index);
        if(index<3){
            setCompareSeries(option_2, copy,index,index_time,index_show,length);
            setCompareLegend(copy);
            setCompareTooltip(copy);
            delete copy.dataZoom;
        }

    }

    var xAxis_show;     // X轴所显示的时间区间
    var legend_SelectedMap={};  //需要记忆图例的选择状态
    function hideDataZoom(){
        legend_SelectedMap=zrUtil.clone(myChart1.component.legend.getSelectedMap());
        xAxis_show=zrUtil.clone(myChart1.component.dataZoom.option.xAxis[0].data);    //记忆缩放
        myChart1.setOption(option_1,false);
    }


    function setCompareTooltip(copy){
        copy.series[1]&&copy.series[1].tooltip&&(copy.series[1].tooltip={show:false});
        copy.series[2]&&copy.series[2].tooltip&&(copy.series[2].tooltip={show:false});
        copy.series[3]&&copy.series[3].tooltip&&(copy.series[3].tooltip={show:false});

        copy.tooltip.formatter=function(params, ticket, callback){
            var date_current=params[0][1];
            var data_current=params[0][2];
            var index_current=getIndexByName(copy.xAxis[0].data,date_current);

            var dateVal = formatShowDate(date_current);
            var result='<table class="table-center">' +
                '<tr><td>'+dateVal;
            //是日要显示周几
            if(isDay())
                 result += ' ('+getWeekDay(dateVal)+')';
            result += '</td><td>'+zrnumber.addCommas(data_current)+'</td></tr>';
            if(copy.series[1]){
                var data_compare=copy.series[1].data[index_current];
                var s=(((data_current-data_compare)/data_compare)*100).toFixed(2);
                dateVal = formatShowDate(copy.xAxis[1].data[index_current]);
                result+='<tr><td>'+dateVal;
                if(isDay())
                    result += ' ('+getWeekDay(dateVal)+')';
                result += '</td><td>'+zrnumber.addCommas(data_compare)+'</td></tr>';
                if(s>0){
                    result+='<tr><td>变化</td><td style="color: orangered">'+s+'%&#8593</td></tr>';
                }else{
                    result+='<tr><td>变化</td><td style="color: greenyellow">'+s+'%&#8595</td></tr>';
                }
            }
            result+='</table>';
            return   result;
        }
    }

    function setCompareLegend(copy){
        copy.legend.data=[copy.series[0].name, copy.series[1].name];
        copy.legend.selectedMode=false;
    }

    function  setCompareSeries(option_day,copy,index,index_time,index_show,length){
        copy.series=[];
        //原来数据
        copy.series.push(zrUtil.clone(option_day.series[index]));
        copy.series[0].type='line';
        copy.series[0].data=option_day.series[index].data.slice(index_show,index_show+length);
        delete  copy.series[0].stack;
        delete  copy.series[0].itemStyle;
        //对比数据
        copy.series.push(zrUtil.clone(option_day.series[index]));
        copy.series[1].type='line';
        copy.series[1].name="对比时间段";
        copy.series[1].xAxisIndex=1;
        delete  copy.series[1].stack;
        delete  copy.series[1].itemStyle;

        copy.series[1].data=option_day.series[index].data.slice(index_time,index_time+length);
        if(length>31){return}
        //对比柱
        copy.series.push({
            tooltip:{show:false},
            show:false,
            name: '对比时间段1',
            type: 'bar',
            stack: '1',
            barWidth:3,
            xAxisIndex:1,
            itemStyle:{
                normal:{
                    color:'rgba(0,0,0,0)'
                },
                emphasis:{
                    color:'rgba(0,0,0,0)'
                }
            },
            data: function(){
                var i=0;
                return $.map(copy.series[1].data,function(val){
                    var tt=copy.series[0].data[i++];
                    if(val<tt){
                        return val;
                    }else{
                        return tt;
                    }
                })
            }()
        });
        copy.series.push({
            tooltip:{show:false},
            name: '变化',
            type: 'bar',
            stack: '1',
            xAxisIndex:1,
            data: function(){
                var i=0;
                return $.map(copy.series[1].data,function(val){
                    var tt=copy.series[0].data[i++];
                    if(val<tt){
                        return tt-val;
                    }else{
                        return {value : val-tt, itemStyle:{ normal:{color:'red'}}};
                        //return val-tt;
                    }
                })
            }()
        });
    }

    function setCompareXaxis(option_day,copy,index_time,index_show,length){
        copy.xAxis=[];
        copy.xAxis.push(zrUtil.clone(option_day.xAxis[0]));
        copy.xAxis.push(zrUtil.clone(option_day.xAxis[0]));
        copy.xAxis[0].data=option_day.xAxis[0].data.slice(index_show,index_show+length);
        copy.xAxis[1].data=option_day.xAxis[0].data.slice(index_time,index_time+length);
    }

    function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
    }

    function formatTime(time){
        return time;
    }

    function getShowDays(){
        return xAxis_show;
    }

    function getAllDays(){
        return option_2.xAxis.data||option_2.xAxis[0].data;
    }
    var EC={
        show:show,
        resize:function(){myChart1.resize();},
        hideDataZoom:hideDataZoom
    };
    //绑定change事件
    $("#customertransfer_product").change(function(){
        changeIndexForTransfer(this);
        var type = 2;       
        EC.show(cate,type);
    });
     //绑定数值change事件
    $("#customertransfer_numtype").change(function(){
        changeNumForTransfer(this);
        var type = 2;       
        EC.show(cate,type);
    });

    $(":button.customer_transfer[dateGrp]").click(function(){
        changeDateGrp(this);
        EC.show(cate,1);
    });


    return EC;
});

